import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
from typing import Optional, List, Dict, Any
import os
from wordcloud import WordCloud
import jieba
import logging

def setup_style(self):
    """设置可视化样式"""
    import matplotlib as mpl
    from matplotlib import font_manager
    
    try:
        # 清除字体缓存
        font_manager._rebuild()
        
        # 获取系统中所有字体
        system_fonts = [f.name for f in font_manager.fontManager.ttflist]
        logger.info(f"系统可用字体数量: {len(system_fonts)}")
        
        # 中文字体优先级列表
        chinese_fonts_priority = [
            'SimHei', 'Microsoft YaHei', 'DejaVu Sans', 
            'WenQuanYi Micro Hei', 'Noto Sans CJK SC', 'Source Han Sans CN',
            'PingFang SC', 'Hiragino Sans GB', 'STHeiti', 'SimSun',
            'Arial Unicode MS'
        ]
        
        # 找到第一个可用的中文字体
        selected_font = None
        for font_name in chinese_fonts_priority:
            if font_name in system_fonts:
                selected_font = font_name
                logger.info(f"选择字体: {selected_font}")
                break
        
        if selected_font:
            # 设置字体
            plt.rcParams['font.family'] = selected_font
            plt.rcParams['font.sans-serif'] = [selected_font] + plt.rcParams['font.sans-serif']
        else:
            logger.warning("未找到中文字体，尝试使用字体文件")
            # 尝试直接使用字体文件
            font_path = self._get_font_path()
            if font_path:
                try:
                    # 直接添加字体文件到字体管理器
                    font_prop = font_manager.FontProperties(fname=font_path)
                    plt.rcParams['font.family'] = [font_prop.get_name()]
                    logger.info(f"使用字体文件: {font_path}")
                except Exception as e:
                    logger.error(f"加载字体文件失败: {e}")
        
        # 确保设置生效
        plt.rcParams['axes.unicode_minus'] = False
        
        # 测试字体
        self._test_chinese_font()
        
    except Exception as e:
        logger.error(f"字体设置失败: {e}")
        # 备用设置
        plt.rcParams['font.sans-serif'] = ['DejaVu Sans', 'Arial']
        plt.rcParams['axes.unicode_minus'] = False
    
    sns.set_style("whitegrid")
    sns.set_palette("husl")
    
    # 设置图表大小和DPI
    plt.rcParams['figure.figsize'] = [10, 6]
    plt.rcParams['figure.dpi'] = 100

fig, ax = plt.subplots(1, 1, figsize=(4, 1))
test_text = "中文测试 Chinese Test 123"
ax.text(0.5, 0.5, test_text, ha='center', va='center', fontsize=10)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.axis('off')